<template>
  <div class="common-container">
    <div class="header">
      <div class="header_left">
        <el-popover placement="bottom" width="460" trigger="click" popper-class="popover" size="small"
          v-model="showPopover">
          <div>
            <el-form label-width="70px" style="margin: 20px 0" class="popover_from">
              <el-form-item size="small" label="组织机构"
                v-if="user.roleName === 'TENANT_ADMIN' || user.roleName === 'ORG_ADMIN'">
                <TreeSearch style="width: 360px; margin-left: 15px" @changeOrgId="changeOrgId2" @onClear="onClear"
                  ref="refTreeSearch" :clearable="user.roleName === 'TENANT_ADMIN' ? true : false">
                </TreeSearch>
              </el-form-item>

              <el-form-item size="small" label="联网单位" v-if="user.roleName != 'PLATFORM_ADMIN'">
                <el-select size="small" style="width: 360px; margin-left: 15px" v-loadMore="loadMore"
                  v-model="selectedValue" placeholder="请选择联网单位" filterable remote :remote-method="remoteMethod"
                  clearable @clear="handleClear" >
                  <el-option v-for="item in orgList" :label="item.orgName" :value="item.id" :key="item.id">
                  </el-option>
                  <div class="div_box" v-loading="loading" :style="loading ? '' : 'display: none;'"></div>
                </el-select>
              </el-form-item>

              <el-form-item size="small" label="任务状态">
                <el-select size="small" style="width: 360px; margin-left: 15px" clearable v-model="status"
                  placeholder="任务状态">
                  <el-option v-for="item in statusList" :label="item.name" :value="item.id" :key="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item size="small" label="任务类型">
                <el-select size="small" style="width: 360px; margin-left: 15px" clearable v-model="type"
                  placeholder="任务类型">
                  <el-option v-for="item in typeList" :label="item.name" :value="item.id" :key="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div class="footer" style="text-align: right">
              <el-button size="small" @click="resetClick" class="cancel-button">重 置</el-button>
              <el-button size="small" class="confirm-button" @click="onSearch">确 定</el-button>
            </div>
          </div>
          <el-button size="small" slot="reference" :class="hasSearch ? 'elhasSearch elhasSearch2' : 'elhasSearch2'"
            style="margin-left: 15px;">
            高级搜索<i class="el-icon-search" style="margin-left: 5px; font-size: 12px"></i></el-button>
        </el-popover>

      </div>
      <div class="header_right">
        <el-button class="el_button" size="small" type="primary" icon="el-icon-refresh" style="margin-left: 15px"
          :loading="loadingRefresh" @click="onRefresh">
          刷新
        </el-button>
      </div>
    </div>
    <div class="content">
      <el-table :data="dataList" class="table" :header-cell-style="headerStyle" v-loading="loadingTable"
          element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(47, 51, 73, 0.3)">
        <el-table-column align="center" label="序号" type="index" width="80" height="30"></el-table-column>
        <el-table-column align="center" prop="name" label="任务名称" min-width="200"
          show-overflow-tooltip></el-table-column>
        <el-table-column align="center" prop="type" label="任务类型" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.type == 1">导入</span>
            <span v-if="scope.row.type == 2">导出</span>
            <span v-if="scope.row.type == 3">设备自动生成</span>
            <span v-if="scope.row.type == 4">设备全量同步</span>
            <span v-if="scope.row.type == 5">监控点自动生成</span>
            <span v-if="scope.row.type == 6">监控点全量同</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="type" label="任务状态" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status == 0" type="warning">执行中</el-tag>
            <el-tag v-if="scope.row.status == 1" type="success">执行完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="createTime" label="创建时间" min-width="140"
          show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="操作" min-width="140">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="下载" placement="bottom" v-if="scope.row.status == 1">
              <i @click="editClick(scope.row)" class="el-icon-download tableBtnIcon"></i>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
              <i @click="delClick(scope.row.id)" class="iconfont shanchu tableBtnIcon"></i>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="page" :limit.sync="limit" :pageSizes="[10, 20, 30, 50]"
        @pagination="getDataList" class="pagination" />
    </div>
  </div>
</template>

<script>
import { reqTaskPage, reqTaskRemove, reqOrgList } from "@api/api.js";
import Pagination from "@components/Pagination.vue";
import tableStyleMixin from "@mixin/table-style";
import { mapState } from "vuex";
import loadMore from "@mixin/loadMore";
import TreeSearch from "@components/TreeSearch.vue";

export default {
  name: "task",
  components: { Pagination, TreeSearch },
  mixins: [tableStyleMixin, loadMore],
  data() {
    return {
      dataList: [],
      loadingTable:false,
      limit: 10,
      page: 1,
      total: 0,
      orgId: "",
      orgList: [], //组织机构
      sysInstanceIndex: 1,
      sysInstanceTotalPages: 10,
      loading: false,
      loadingRefresh: false,
      status: "",
      type: "",
      statusList: [
        {
          id: 0,
          name: "执行中",
        },
        {
          id: 1,
          name: "执行完成",
        },
      ],
      typeList: [
        {
          id: 1,
          name: "导入",
        },
        {
          id: 2,
          name: "导出",
        },
      ],
      targetId: "",
      defaultCheckedKeys: "",
      orgName: "",
      parentId: "",
      selectedValue: "",
      hasSearch: false,
      showPopover: false,
    };
  },
  computed: {
    ...mapState(["user", "spacesManage"]),
  },
  async created() {
    // console.log(this.$route.params, "this.$route.params");
    if (this.$route.params && this.$route.params.orgId) {
      this.targetId = this.$route.params.orgId;
    }
  },
  mounted() {
    // if (
    //   this.user.roleName == "ORG_ADMIN" ||
    //   this.user.roleName == "INSTERALL_USER"
    // ) {
    //   // 组织||装维
    //   this.targetId = this.spacesManage.organizationInfo.orgId;
    //   this.getDataList();
    // } else {
    //   this.getDataList();
    // }
    this.getDataList();
    if (this.user.roleName == 'INSTERALL_USER' || this.user.roleName == 'UNIT_ADMIN') {
      this.getOrgList()
    }
  },
  methods: {
    // 搜索
    async onSearch() {
      this.showPopover = false;
      this.getInitDataList()
    },
    // 高级搜索重置
    async resetClick() {
      this.parentId = ''
      this.selectedValue = ''
      this.status = ''
      this.type = ''
      await this.getInitDataList()
      if (this.$refs.refTreeSearch) {
        this.$refs.refTreeSearch.onclose()
      }
      if (this.user.roleName != 'INSTERALL_USER' && this.user.roleName != 'UNIT_ADMIN') {
        this.orgList = []
      }
    },
    changeOrgId2(instanceId) {
      this.parentId = instanceId.id
      this.handleClear();
    },
    onClear() {
      this.parentId = ''
      this.selectedValue = '';
      this.orgName = '';
      this.sysInstanceIndex = 1;
      this.sysInstanceTotalPages = 10;
      this.orgList = []
      this.changeOrgId()
    },
    // 选择组织机构
    changeOrgId() {
      this.page = 1;
      this.limit = 10;
      this.getDataList();
    },

    // 刷新
    onRefresh() {
      this.page = 1;
      this.limit = 10;
      this.loadingRefresh = true;
      this.getDataList("refesh");
      //   this.loadingRefresh = false;
    },

    // 清空
    handleClear() {
      this.selectedValue = '';
      this.orgName = '';
      this.sysInstanceIndex = 1;
      this.sysInstanceTotalPages = 10;
      this.orgList = []
      this.getOrgList()
    },
    // 远程搜索
    async remoteMethod(query) {
      this.selectedValue = query //保留输入的值
      this.orgName = query;
      this.sysInstanceIndex = 1;
      this.sysInstanceTotalPages = 10;
      this.orgList = []
      this.getOrgList()
    },
    async loadMore() {
      if (this.sysInstanceIndex >= Math.ceil(this.sysInstanceTotalPages / 10))
        return;
      this.sysInstanceIndex++;
      this.loading = true;
      // 获取列表数据的方法
      await this.getOrgList();
      this.loading = false;
    },
    // 获取组织机构列表
    async getOrgList(flag) {
      var res = await reqOrgList({
        userId: this.user.userId,
        roleName: this.user.roleName,
        tenantId: this.user.tenantId,
        parentId: this.parentId,
        type: "4"
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.sysInstanceTotalPages = res.data.total;

      if (this.$route.params.orgId != null && this.$route.params.orgId != 0) {
        // 告警导出跳转过来
        this.orgList = [
          ...this.orgList,
          ...res.data.rows.filter(
            (item) => item.id != this.$route.params.orgId
          ),
        ]; //过滤
      } else {
        this.orgList = [...this.orgList, ...res.data.rows];
      }
      // 告警导出跳转过来
      if (
        this.$route.params.orgId != null &&
        flag &&
        this.$route.params.orgId != 0
      ) {
        this.orgList.push({
          id: this.$route.params.orgId,
          orgName: this.$route.params.orgName,
        });
        this.orgId = this.$route.params.orgId;
        // return;
      } else {
        // if (flag && this.user.roleName == 'TENANT_ADMIN') {
        //     this.orgId = '';
        // } else if(flag && this.user.roleName == 'ORG_ADMIN'){
        //     this.orgId = res.data.rows[0].id;
        // }
        this.orgId = "";
      }
    },

    // 获取列表
    async getDataList(isRefresh = "") {
      this.loadingTable=true;
      const res = await reqTaskPage(this.page, this.limit, {
        tenantId: this.user.tenantId,
        orgId: this.selectedValue == '' ? this.parentId : this.selectedValue,//机构||单位
        status: this.status,
        type: this.type,
      });
      this.loadingTable=false;
      if (isRefresh == "refesh") {
        this.loadingRefresh = false;
      }
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.hasSearch = (this.parentId || this.selectedValue || this.status || this.type) ? true : false
      this.dataList = res.data.rows;
      this.total = res.data.total;
    },
    getInitDataList() {
      this.page = 1;
      this.limit = 10;
      this.getDataList();
    },
    editClick(row) {
      // window.open(row.url)
      window.location.href = row.url;
    },
    // 删除
    async delClick(id) {
      const result = await this.$confirm(
        "此操作将永久删除该报表, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => { });
      if (result !== "confirm") return;
      const res = await reqTaskRemove(id);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("删除成功");
      this.getInitDataList();
    },
  },
};
</script>

<style scoped lang="less">
@import url("~@views/style/tablePage.less");
@import url("~@views/style/tree.less"); //左侧组织机构样式

::v-deep .el_button.el-button--small {
  background: #7367f0;
  color: #fff;
  border: none;
}

// 下拉框加载开始
.div_box {
  height: 276px;
  position: absolute;
  top: -1px;
  left: -1px;
  width: 100%;
  z-index: 9999;
  // background: red;
  // opacity: 0.5;
}

::v-deep .el-loading-mask {
  border-radius: 4px;
}

// 下拉框加载结束

// 高级搜索
::v-deep .el-button--primary {
  background-color: #7367f0;
  border: 1px solid #7367f0;
  color: #fff;
}

::v-deep .el-form-item__label {
  color: @primaryThemeTxtColor2;
  padding: 0px;
}

::v-deep .el-input__inner {
  color: var(--primaryContentTxt, #f1f1f1) !important;
}

.dropdown {
  background: #7367f0;
  color: #fff;
  border: none;
}

::v-deep .el-button--small {
  border: none;
}

// 高级搜索----------</style>
